﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace FileListMaker
{
    public interface IConfigReaderWriter
    {
        void Read(Stream stream);
        void Write(Stream stream);
    }

    public interface IControlConfigurationTarget
    {
        void LoadConfiguration(string id);
        IConfigReaderWriter ConfigReaderWriter { get; }
    }

    public interface IControlConfiguration
    {
        void Add(IControlConfigurationTarget target);
        void Save();
    }

    public class ControlConfiguration
    {
        private class DefaultControlCongiruration : IControlConfiguration
        {
            private List<IControlConfigurationTarget> targets = new List<IControlConfigurationTarget>();

            private string ConfigFileFullPath
            {
                get { return System.IO.Path.Combine(System.Environment.CurrentDirectory, "app.control.config"); }
            }

            public void Add(IControlConfigurationTarget target)
            {
                using (var stream = new FileStream(ConfigFileFullPath, FileMode.OpenOrCreate))
                {
                    targets.Add(target);
                    target.ConfigReaderWriter.Read(stream);
                }
            }

            public void Save()
            {
                File.Delete(ConfigFileFullPath);
                using (var stream = new FileStream(ConfigFileFullPath, FileMode.CreateNew))
                {
                    for (int i = 0; i < targets.Count; i++)
                    {
                        targets[i].ConfigReaderWriter.Write(stream);
                    }

                    stream.Flush();
                }
            }
        }

        private static IControlConfiguration current = null;
        public static IControlConfiguration Current
        {
            get
            {
                if (current == null)
                    current = new DefaultControlCongiruration();
                return current;
            }
            set
            {
                current = value;
            }
        }
    }
}
